# Makefile

target_name := main

CUR_DIR := $(shell pwd)
OBJ_DIR := build
SRC_DIR := .


OS = $(shell uname -o)
ARCH = $(shell uname -m)

MSYS := Msys
LINUX := Linux

i686 := i686
x86_64 := x86_64


CC := gcc
CFLAGS = -Wall -O2 -std=c99 


SRC_DIRS := $(shell find $(SRC_DIR) -maxdepth 3 -type d)
OBJ_DIRS += $(OBJ_DIR)
OBJ_DIRS += $(filter-out $(SRC_DIR), $(patsubst $(SRC_DIR)/%, $(OBJ_DIR)/%, $(SRC_DIRS)))

source 	:= $(foreach n, $(SRC_DIRS), $(wildcard $(n)/*.c))
objs := $(patsubst $(SRC_DIR)/%.c, $(OBJ_DIR)/%.o, $(source))
deps := $(patsubst %.o, %.d, $(objs))

target := $(target_name)


.PHONY: all checkdir format clean cleanall

all: checkdir $(target)
	@echo '<$(target_name)> was built!'


$(target): $(objs)
	$(CC) -o $@ $^ $(LDFLAGS)


$(OBJ_DIR)/%.d: $(SRC_DIR)/%.c
	@set -e; rm -f $@; \
	$(CC) -MM $(CPPFLAGS) $< > $@.$$$$; \
	sed 's,\($*\)\.o[ :]*, $(OBJ_DIR)\/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$

-include $(deps)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
	$(CC) -o $@ -c $< $(CFLAGS)

checkdir:
	@if test ! -d $(OBJ_DIR); \
	then \
		echo 'mkdir -p $(OBJ_DIRS)'; \
		mkdir -p $(OBJ_DIRS); \
	fi

format:$(source)
	@if test -x /usr/bin/astyle; \
	then \
		astyle $^ --style=linux -j -n; \
	fi
	
#$(objects): %.o : %.c
#	$(CC) $(CFLAGS) -o $(OBJ_DIR)/$@ -c $(SRC_DIR)/$<

clean:
	rm -rf $(target) $(objs) $(deps)

cleanall:
	rm -rf $(target) $(objs) $(deps) $(OBJ_DIR)

show:
	@echo 'CUR_DIR    :' $(CUR_DIR)
	@echo 'SRC_DIRS   :' $(SRC_DIRS)
	@echo 'sources    :' $(source)
	@echo 'OBJ_DIRS   :' $(OBJ_DIRS)
	@echo 'objects    :' $(objs)
	@echo 'depends    :' $(deps)
	@echo 'target     :' $(target_name)
